package com.mnnu.service.impl;

import com.mnnu.anno.Log;
import com.mnnu.mapper.DeptLogMapper;
import com.mnnu.mapper.DeptMapper;
import com.mnnu.mapper.EmpMapper;
import com.mnnu.pojo.Dept;
import com.mnnu.pojo.DeptLog;
import com.mnnu.service.DeptLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptService implements com.mnnu.service.DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Transactional(rollbackFor = Exception.class) //业务层方法/类/接口上  将当前方法交给spring进行事务处理 默认rollbackFor = RuntimeException.class
    @Override
    public void deleteById(Integer id) {
        try {
            deptMapper.deleteById(id); //根据id删除部门
            empMapper.deleteByDeptId(id); //根据部门id删除员工信息
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行解散部门，此次解散部门id:" + id);
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
